﻿using System;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Nasa8x.Core;

namespace Nasa8x.Web.UI
{
    [ToolboxData("<{0}:GridViewEx runat=\"server\"></{0}:GridViewEx>")]
    public class GridView : System.Web.UI.WebControls.GridView
    {
        
        #region Properties
        public bool ResetPageIndexOnSort
        {
            get
            {
                object _o = ViewState["ResetPageIndexOnSort"];
                if (_o != null)
                {
                    return (bool)_o;
                }
                return false;
            }
            set { ViewState["ResetPageIndexOnSort"] = value; }

        }

        public bool ClientScript
        {
            get
            {
                object _o = ViewState["ClientScript"];
                if (_o != null)
                {
                    return (bool)_o;
                }
                return true;
            }
            set { ViewState["ClientScript"] = value; }

        }

        /// <summary>
        /// Returns the current sort expression for this GridView saved in the ViewState.
        /// </summary>
        public string SortExpressionExtension
        {
            get { return (ViewState["SortExtension"] != null) ? (string)ViewState["SortExtension"] : null; }
            set { ViewState["SortExtension"] = value; }
        }

        /// <summary>
        /// Returns the current sort direction (reversed or not) for this GridView saved in the ViewState.
        /// </summary>
        public bool SortReverse
        {
            get { return (ViewState["SortReverse"] != null) ? (bool)ViewState["SortReverse"] : false; }
            set { ViewState["SortReverse"] = value; }
        }


        public string CssClassRowSorted
        {
            get
            {
                return (string)ViewState["CssClassRowSorted"];

            }
            set { ViewState["CssClassRowSorted"] = value; }
        }

        public string CssClassHeaderSortedAsc
        {
            get
            {
                return (string)ViewState["CssClassHeaderSortedAsc"];

            }
            set { ViewState["CssClassHeaderSortedAsc"] = value; }
        }
        public string CssClassHeaderSortedDesc
        {
            get
            {
                return (string)ViewState["CssClassHeaderSortedDesc"];

            }
            set { ViewState["CssClassHeaderSortedDesc"] = value; }
        }

        #endregion


        #region OnRowDataBound

        internal void OnRowDataBound(object sender, GridViewRowEventArgs args)
        {
            GridView _gridView = (GridView)sender;
            if (_gridView.SortExpression.Length > 0)
            {
                int _cellIndex = -1;
                foreach (DataControlField _field in _gridView.Columns)
                {
                    if (_field.SortExpression == _gridView.SortExpression)
                    {
                        _cellIndex = _gridView.Columns.IndexOf(_field);
                        break;
                    }
                }
                if (_cellIndex > -1)
                {
                    if (args.Row.RowType == DataControlRowType.Header)
                    {
                        //  this is a header row,set the sort style
                        args.Row.Cells[_cellIndex].CssClass +=
                            (_gridView.SortDirection == SortDirection.Ascending ? " " + CssClassHeaderSortedAsc : " " + CssClassHeaderSortedDesc);
                    }

                    if (args.Row.RowType == DataControlRowType.DataRow && !String.IsNullOrEmpty(CssClassRowSorted))
                    {

                        //to handle changing the color of which column is being sorted
                        args.Row.Cells[_cellIndex].Attributes.Add("class", CssClassRowSorted);

                    }
                }
            }
        }

        #endregion

        #region Override OnPreRender


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            RowDataBound += OnRowDataBound;

        }

        #endregion

        #region ObjectDataSource Interaction
        public void DataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
           
            // If sorting is specified or defaults are specified, sort the list returned by
            // the Select operation in place.
            if (!String.IsNullOrEmpty(SortExpressionExtension))
            {
                ComparerExtension _ce = new ComparerExtension(SortExpressionExtension, SortReverse);
                ArrayList.Adapter((IList)e.ReturnValue).Sort(_ce);
                //SortExtensions.Sort((IList) e.ReturnValue, SortExpressionExtension);
                //SortExtensions.OrderBy(((IList)e.ReturnValue).AsQueryable(),SortExpressionExtension);


            }
            return;
        }

        /// <summary>
        /// Get the DataSource object referenced by this object.
        /// </summary>
        /// <returns>The ObjectDataSource used by this GridView.</returns>
        private ObjectDataSource GetDataSource()
        {
            if (DataSource != null)
            {
                return (ObjectDataSource)DataSource;
            }
            if (DataSourceID != null && Parent.FindControl(DataSourceID) != null)
            {
                return (ObjectDataSource)Parent.FindControl(DataSourceID);
            }
            return null;
        }

        private void AttachDataSourceEvent()
        {
            ObjectDataSource ds = GetDataSource();
            if (ds != null) { ds.Selected += DataSource_Selected; }
        }
        #endregion

        #region Life Cycle
        protected override void OnSorting(GridViewSortEventArgs e)
        {
            // If the sort expression is the same as the current one, then reverse the sort order.
            if (SortExpressionExtension == e.SortExpression)
            {
                SortReverse = !SortReverse;
            }
            // Otherwise, use ascending sort order, and move to the first page.
            else
            {
                SortReverse = false;
                if (ResetPageIndexOnSort)
                    PageIndex = 0;
            }
            SortExpressionExtension = e.SortExpression;
            DataBind();
            e.Cancel = true;
        }

        protected override void OnLoad(EventArgs e)
        {
            AttachDataSourceEvent();
            base.OnLoad(e);
        }
        #endregion

        #region Render

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            if(ClientScript)
            {
                StringBuilder _sb = new StringBuilder();
                _sb.Append("<script type=\"text/javascript\">");

                _sb.Append(
                            @"$(function() {
                                $('.gridview tr.row')
                                .hover(
                                    function() {
                                        $(this).addClass('row-hover');
                                    },
                                    function() {
                                        $(this).removeClass('row-hover');
                                    })
                                .click(function(e) {
                                    if (!e.ctrlKey) {
                                        $('.gridview tr').removeClass('row-selected');
                                    };
                                    $(this).addClass('row-selected');

                                })
                        });
                    ");

                _sb.Append("</script>");

                writer.Write(_sb);
            }
            

        }

        #endregion
    }
}
